<template>
  <div>
    <el-form :inline="true">
      <el-form-item label="编号">
        <el-input v-model="reportQueryParam.Code">
          <el-button slot="append" icon="el-icon-search" @click="queryMetaData" />
        </el-input>
      </el-form-item>
      <el-form-item label="TOKEN">
        <el-input v-model="Token" />
      </el-form-item>
      <el-row>
        <el-button v-loading="execLoading" @click="doQuery">
          执行
        </el-button>
      </el-row>
    </el-form>
    <el-row style="margin-top: 20px" :gutter="20">
      <el-col :span="16">
        <el-collapse v-model="activeNames">
          <el-collapse-item title="入参" name="1">
            <el-row>
              <ace-editor
                ref="ace"
                :config="aceOption"
                :custom-complete-data="customCompleteData"
                @content-change="v=>this.requestJson=v"
              />
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="返回结果" name="2">
            <el-row>
              <ace-editor ref="ace2" :config="aceOption2" />
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="SQL" name="3">
            <el-input v-for="item in Sql" :key="item" :value="item" :rows="8" type="textarea" />
          </el-collapse-item>
          <el-collapse-item title="Count SQL" name="4">
            <el-row v-if="CountSql">
              <el-input v-for="item in CountSql" :key="item" :value="item" :rows="8" type="textarea" />
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-col>
      <el-col :span="8">
        <el-table
          :data="metaData.RequestReportParams"
          border
          fit
          highlight-current-row
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column label="属性" prop="AttributeName" />
          <el-table-column label="名称" prop="Name" />
          <el-table-column label="类型">
            <template slot-scope="scope">
              {{ scope.row.Type | dictFilter(enums.reportParamTypeEnum) }}
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import reportApi from '@/api/report'
import reportFormTypeEnum from '@/enums/report/reportFormTypeEnum'
import reportParamTypeEnum from '@/enums/report/reportParamTypeEnum'
import dataAccessEnum from '@/enums/sys/dataAccessEnum'
import AceEditor from '@/components/AceEditor'
import { Parser } from 'node-sql-parser'
import sqlFormatter from 'sql-formatter'
// eslint-disable-next-line no-unused-vars
import graphqlSimple from '@/utils/graphqlSimple'
// eslint-disable-next-line no-unused-vars
import axios from 'axios'

export default {
  name: 'TestJson',
  components: {
    AceEditor
  },
  props: {
    code: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      reportQueryParam: {
        Code: this.code,
        DataAccess: null
      },
      Token: '',
      activeNames: ['1'],
      metaData: {},
      aceOption: {
        lang: 'json',
        theme: 'chrome',
        fontSize: 20
      },
      aceOption2: {
        lang: 'json',
        theme: 'chrome',
        fontSize: 8,
        readOnly: true

      },
      enums: { reportFormTypeEnum, reportParamTypeEnum, dataAccessEnum },
      params: [],
      requestJson: null,
      Sql: [],
      CountSql: [],
      execLoading: false,
      Parser: new Parser()
    }
  },

  computed: {
    customCompleteData() {
      var data = []
      if (this.metaData.RequestReportParams) {
        for (const param of this.metaData.RequestReportParams) {
          const item = {}
          item.meta = '参数'
          item.caption = param.AttributeName
          item.value = param.AttributeName
          item.score = 200
          data.push(item)
        }
      }

      console.log('data', data)
      return data
    }
  },
  mounted() {
    if (this.reportQueryParam.Code) {
      this.queryMetaData()
    }
  },
  methods: {
    queryMetaData() {
      this.metaData = {}
      this.queryResult = []
      this.tableHeaders = []
      reportApi.reportDetailByCode(this.reportQueryParam.Code).then(response => {
        if (response.data) {
          this.metaData = response.data.reportDetailByCode
          var requestEntity = {}
          if (this.metaData.RequestReportParams) {
            for (const requestReportParam of this.metaData.RequestReportParams) {
              requestEntity[requestReportParam.AttributeName] = ''

              if (requestReportParam.Type === reportParamTypeEnum.TEXT.value) {
                requestEntity[requestReportParam.AttributeName] = ''
              }
              if (requestReportParam.Type === reportParamTypeEnum.NUMBER.value) {
                requestEntity[requestReportParam.AttributeName] = 0
              }
              if (requestReportParam.Type === reportParamTypeEnum.DATETIME.value) {
                requestEntity[requestReportParam.AttributeName] = '2020-02-02 12:12:12'
              }
              if (requestReportParam.Type === reportParamTypeEnum.SELECT.value) {
                requestEntity[requestReportParam.AttributeName] = 0
              }
              if (requestReportParam.Type === reportParamTypeEnum.DATE.value) {
                requestEntity[requestReportParam.AttributeName] = '2020-02-02'
              }
              if (requestReportParam.Type === reportParamTypeEnum.TIME.value) {
                requestEntity[requestReportParam.AttributeName] = '12:12:12'
              }
              if (requestReportParam.Type === reportParamTypeEnum.MULTI_SELECT.value) {
                requestEntity[requestReportParam.AttributeName] = []
              }
              if (requestReportParam.Type === reportParamTypeEnum.PROVINCE_CITY_AREA.value) {
                requestEntity[requestReportParam.AttributeName] = {}
                requestEntity[requestReportParam.AttributeName].district_id = ''
                requestEntity[requestReportParam.AttributeName].city_id = ''
                requestEntity[requestReportParam.AttributeName].province_id = ''
              }
            }
            var j = JSON.stringify(requestEntity, null, '\t')
            this.$refs.ace.$ace.setValue(j)
          } else {
            this.$refs.ace.$ace.setValue('{}')
          }
        }
      })
    },
    doQuery() {
      var postData = {}
      postData.Code = this.reportQueryParam.Code
      postData.Params = JSON.parse(this.$refs.ace.$ace.getValue()) || {}
      if (this.reportQueryParam.DataAccess) {
        postData.Params.auths_DataAccess = this.reportQueryParam.DataAccess
      }
      this.execLoading = true
      var config = {}
      config.headers = {}
      config.headers['content-type'] = 'application/json'

      if (this.Token) {
        config.headers['Authorization'] = this.Token
      }
      axios.post(process.env.VUE_APP_GRAPHQL_HTTP, graphqlSimple(`mutation ($req: TestReportReq!) {
            testReport(Req: $req){
                List
                Count
                Sql
                Detail
                CountSql
                Aggregate
            }
        }`)({ req: postData }), config).then(response => {
        console.log(response)
        if (response.data && response.data.data) {
          var queryResult = response.data.data.testReport

          this.Sql = []
          if (queryResult.Sql) {
            for (const item of queryResult.Sql) {
              this.Sql.push(sqlFormatter.format(item))
            }
          }
          this.CountSql = []
          if (queryResult.CountSql) {
            for (const item of queryResult.CountSql) {
              this.CountSql.push(sqlFormatter.format(item))
            }
          }
          this.activeNames = ['1', '2']
          const r = { List: queryResult.List, Detail: queryResult.Detail, Count: queryResult.Count, Aggregate: queryResult.Aggregate }
          this.$refs.ace2.$ace.setValue(JSON.stringify(r, null, '\t'))
        } else {
          throw new Error(response.data.errors[0].message)
        }
      }).catch((err) => {
        this.$refs.ace2.$ace.setValue(err.message)
      }).finally(() => {
        this.execLoading = false
      })
    }

  }
}
</script>

<style>
#app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>
